package com.billing.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.billing.persistance.dao.IGenericDAO;
import com.billing.persistance.entities.TechUser;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    
    @Autowired
    @Qualifier(value="techUserDAO")
    private IGenericDAO<TechUser, Long> userDAO;
    
    @Transactional (readOnly = true)
    public UserDetails loadUserByUsername(String name)    throws UsernameNotFoundException, DataAccessException {

        List<TechUser> list = userDAO.getList(" where login = '" + name + "'");
        
        if (list.size() > 1){
            throw new DuplicateKeyException("Multiple users with the same username");
        }
        
        if (list.size() == 1){
            return list.get(0);
        }
        
        
        return null;
    }



}

